package com.ucsc.mit.system.login;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.office.automate.dto.convertors.UserAuthenticatorConvertor;
import com.office.automate.exception.framework.FrontierVisibleException;
import com.office.automate.model.authenticate.UserAuthenticator;
import com.office.automate.service.def.authenticate.SystemLoginAuthenticationService;
import com.office.automate.service.impl.authenticate.SystemLoginAuthenticationServiceImplementer;
import com.office.automate.validation.framework.ValidatorObject;

/**
 * Servlet implementation class SystemLoginControle
 */
@WebServlet("/SystemLoginControle")
public class SystemLoginControle extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public SystemLoginControle() {

    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserAuthenticator anUserAuthenticator = null;
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
		try {
			anUserAuthenticator = new UserAuthenticatorConvertor().convertAuthenticatorRequest(request);
			SystemLoginAuthenticationService systemLoginAuthenticationService = 
														new SystemLoginAuthenticationServiceImplementer();

			HashMap<String, FrontierVisibleException> fieldValidationErrors = systemLoginAuthenticationService.validateFieldData(anUserAuthenticator);
			if (fieldValidationErrors != null) {
				request.setAttribute("UserAuthenticator", anUserAuthenticator);
				request.setAttribute("FieldValidationErrors", new ValidatorObject(fieldValidationErrors));
				dispatcher.forward(request, response);		
			} else {
				systemLoginAuthenticationService.validateCredentials(anUserAuthenticator);
				UserAuthenticator authorizedUser = systemLoginAuthenticationService.getSuccessfulAuthenticatedDetails();
				HttpSession session = request.getSession(true);
				session.setAttribute("currentSessionUser", authorizedUser);
				response.sendRedirect("jsp/HomePage.jsp");
			}
		} catch (FrontierVisibleException e) {
			request.setAttribute("OperationalError", e);
			dispatcher.forward(request, response);
		}
	}
}
